'use client'

import { useState, useEffect } from 'react'
import { MainLayout } from '@/components/layout/main-layout'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { UserDetailInline } from '@/components/user-detail-inline'
import { Search, User, Users, Activity, MapPin, Calendar, Phone, Eye, Filter, ArrowLeft } from 'lucide-react'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

interface UserInfo {
  id: number
  mobile: string
  cc: number
  name: string
  avatar?: string
  gender: number
  age: number
  height: string
  weight: string
  city: string
  healthLogsCount?: number // 标记为可选
  createTime: string
  lastActiveTime: string
}

interface UsersResult {
  users: UserInfo[]
  pagination: {
    page: number
    limit: number
    total: number
    pages: number
  }
}

function UsersContent() {
  const [mobile, setMobile] = useState('')
  const [name, setName] = useState('')
  const [userId, setUserId] = useState('')
  const [loading, setLoading] = useState(false)
  const [usersResult, setUsersResult] = useState<UsersResult | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
  const [viewMode, setViewMode] = useState<'list' | 'detail'>('list')

  // 页面加载时获取用户列表
  useEffect(() => {
    handleSearch(1)
  }, [])

  const handleSearch = async (page = 1) => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (mobile) params.append('mobile', mobile)
      if (name) params.append('name', name)
      if (userId) params.append('user_id', userId)
      params.append('page', page.toString())
      params.append('limit', '20')

      const response = await fetch(`/api/users?${params}`)
      const result = await response.json()

      if (result.success) {
        setUsersResult(result.data)
        setCurrentPage(page)
      } else {
        alert(result.message || '查询失败')
      }
    } catch (error) {
      console.error('查询错误:', error)
      alert('查询失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  const clearFilters = () => {
    setMobile('')
    setName('')
    setUserId('')
    handleSearch(1)
  }

  const formatTime = (timeStr: string) => {
    try {
      return format(new Date(timeStr), 'yyyy-MM-dd HH:mm', { locale: zhCN })
    } catch (e) {
      return '未知'
    }
  }

  const getGenderText = (gender: number) => {
    switch (gender) {
      case 1: return '男'
      case 2: return '女'
      default: return '未知'
    }
  }

  const getGenderColor = (gender: number) => {
    switch (gender) {
      case 1: return 'bg-blue-100 text-blue-800'
      case 2: return 'bg-pink-100 text-pink-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getUserInitials = (name: string) => {
    if (!name) return 'U'
    return name.length > 1 ? name.substring(0, 2) : name[0]
  }

  const handleViewDetail = (userId: number) => {
    setSelectedUserId(userId)
    setViewMode('detail')
  }

  const handleBackToList = () => {
    setSelectedUserId(null)
    setViewMode('list')
  }

  // 如果是详情模式，显示用户详情
  if (viewMode === 'detail' && selectedUserId) {
    return (
      <UserDetailInline 
        userId={selectedUserId} 
        onBack={handleBackToList}
      />
    )
  }

  // 默认显示用户列表
  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-gray-900">用户管理</h1>
          <p className="text-sm text-gray-500 mt-1">管理和查看系统用户信息</p>
        </div>
        <div className="flex items-center space-x-2">
          <Button variant="outline" size="sm">
            <Users className="w-4 h-4 mr-1" />
            导出用户
          </Button>
        </div>
      </div>

      {/* 查询条件 */}
      <Card>
        <CardHeader className="pb-4">
          <CardTitle className="text-lg flex items-center">
            <Filter className="w-5 h-5 mr-2" />
            查询条件
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="space-y-2">
              <Label htmlFor="mobile">手机号</Label>
              <Input
                id="mobile"
                placeholder="输入手机号"
                value={mobile}
                onChange={(e) => setMobile(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="name">用户姓名</Label>
              <Input
                id="name"
                placeholder="输入用户姓名"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="userId">用户ID</Label>
              <Input
                id="userId"
                placeholder="输入用户ID"
                value={userId}
                onChange={(e) => setUserId(e.target.value)}
              />
            </div>
          </div>
          <div className="flex items-center space-x-2 mt-4">
            <Button onClick={() => handleSearch(1)} disabled={loading}>
              {loading ? '查询中...' : '查询'}
            </Button>
            <Button variant="outline" onClick={clearFilters}>
              清空条件
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 统计信息 */}
      {usersResult && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <Users className="w-6 h-6 text-blue-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">总用户数</p>
                  <p className="text-2xl font-bold text-gray-900">{usersResult.pagination.total.toLocaleString()}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-green-100 rounded-lg">
                  <User className="w-6 h-6 text-green-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">当前页用户</p>
                  <p className="text-2xl font-bold text-gray-900">{usersResult.users.length}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <Calendar className="w-6 h-6 text-purple-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">总页数</p>
                  <p className="text-2xl font-bold text-gray-900">{usersResult.pagination.pages.toLocaleString()}</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-4">
              <div className="flex items-center">
                <div className="p-2 bg-orange-100 rounded-lg">
                  <Activity className="w-6 h-6 text-orange-600" />
                </div>
                <div className="ml-4">
                  <p className="text-sm font-medium text-gray-500">当前页</p>
                  <p className="text-2xl font-bold text-gray-900">{usersResult.pagination.page}</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 用户列表 */}
      {usersResult && (
        <Card>
          <CardHeader>
            <CardTitle>用户列表</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-3">用户信息</th>
                    <th className="text-left p-3">联系方式</th>
                    <th className="text-left p-3">基本信息</th>
                    <th className="text-left p-3">健康记录</th>
                    <th className="text-left p-3">注册时间</th>
                    <th className="text-left p-3">最后活跃</th>
                    <th className="text-left p-3">操作</th>
                  </tr>
                </thead>
                <tbody>
                  {usersResult.users.map((user) => (
                    <tr key={user.id} className="border-b hover:bg-gray-50">
                      <td className="p-3">
                        <div className="flex items-center space-x-3">
                          <Avatar className="w-10 h-10">
                            <AvatarImage src={user.avatar} alt={user.name} />
                            <AvatarFallback className="bg-blue-100 text-blue-600">
                              {getUserInitials(user.name)}
                            </AvatarFallback>
                          </Avatar>
                          <div>
                            <p className="font-medium text-gray-900">{user.name || '未设置姓名'}</p>
                            <p className="text-xs text-gray-500">ID: {user.id}</p>
                          </div>
                        </div>
                      </td>
                      <td className="p-3">
                        <div className="flex items-center space-x-1">
                          <Phone className="w-4 h-4 text-gray-400" />
                          <span className="font-mono text-sm">
                            {user.mobile ? `+${user.cc || 86} ${user.mobile}` : '未绑定'}
                          </span>
                        </div>
                        {user.city && (
                          <div className="flex items-center space-x-1 mt-1">
                            <MapPin className="w-4 h-4 text-gray-400" />
                            <span className="text-xs text-gray-500">{user.city}</span>
                          </div>
                        )}
                      </td>
                      <td className="p-3">
                        <div className="space-y-1">
                          <Badge className={getGenderColor(user.gender)}>
                            {getGenderText(user.gender)}
                          </Badge>
                          <div className="text-xs text-gray-500">
                            {user.age > 0 && <span>年龄: {user.age}岁</span>}
                            {user.height !== '0' && user.height && (
                              <span className="ml-2">身高: {user.height}cm</span>
                            )}
                            {user.weight !== '0' && user.weight && (
                              <span className="ml-2">体重: {user.weight}kg</span>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="p-3">
                        <div className="flex items-center space-x-1">
                          <Activity className="w-4 h-4 text-green-500" />
                          <span className="font-medium text-green-600">
                            {user.healthLogsCount && user.healthLogsCount > 0 ? 
                              `${user.healthLogsCount.toLocaleString()} 条` : 
                              '点击查看详情'
                            }
                          </span>
                        </div>
                      </td>
                      <td className="p-3 text-xs text-gray-500">
                        {user.createTime ? formatTime(user.createTime) : '未知'}
                      </td>
                      <td className="p-3 text-xs text-gray-500">
                        {user.lastActiveTime ? formatTime(user.lastActiveTime) : '从未活跃'}
                      </td>
                      <td className="p-3">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleViewDetail(user.id)}
                        >
                          <Eye className="w-4 h-4 mr-1" />
                          查看详情
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* 分页 */}
            {usersResult.pagination.pages > 1 && (
              <div className="flex items-center justify-between mt-6">
                <div className="text-sm text-gray-500">
                  第 {usersResult.pagination.page} 页，共 {usersResult.pagination.pages} 页
                </div>
                <div className="flex space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleSearch(currentPage - 1)}
                    disabled={currentPage <= 1 || loading}
                  >
                    上一页
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleSearch(currentPage + 1)}
                    disabled={currentPage >= usersResult.pagination.pages || loading}
                  >
                    下一页
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 空状态 */}
      {!usersResult && !loading && (
        <Card>
          <CardContent className="text-center py-12">
            <Users className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">加载用户列表</h3>
            <p className="text-gray-500">正在获取用户数据...</p>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

export default function UsersPage() {
  return (
    <MainLayout title="用户管理">
      <UsersContent />
    </MainLayout>
  )
}